package com.yan.springbootstudy.common.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class MutiDataSource extends AbstractRoutingDataSource {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	protected Object determineCurrentLookupKey() {
		logger.debug("switch datasource");
		DataOperationContext dataOperationContext = DataOperationContextHolder.getDataOperationContext();
		// 根据用户ID判断，除2取余，0连库，1连库2, 用户id默认为整型，如果是字符型，可以考虑取hashcode
		int userId4int = Integer.parseInt(dataOperationContext.getUserId());
		switch (userId4int % 2) {
		case 0:
			logger.debug("datasource1");
			return "datasource1";
		case 1:
			logger.debug("datasource2");
			return "datasource2";
		default:
			logger.debug("datasource1");
			return "datasource1";
		}
	}

}
